$(function () {
	var url = location.search;
	var brandName=decodeURI(url);
	var brandId="";
	if(url!=null && url!="") {
		brandName = brandName.split("=")[1];
		vm.q.brandId = brandName;
		vm.q.source=1;
		console.log(vm.q.brandId);
		vm.reload();
	}
})
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/barticleinfo/queryList',
        datatype: "json",
        colModel: [
			{ label: 'id', name: 'id', index: 'id',align: "center", width: 60, key: true},
			{ label: '文章名称', name: 'articleTitle', index: 'article_title',align: "center", width: 220,
				formatter:function(value,options,rowData){
				var id=rowData['id'];
				var del=rowData["articleStatus"];
				var content="";
				var page = $("#jqGrid").jqGrid('getGridParam','page');
				if(del==0){
					content= "<a style='color: red' onclick=vm.openArticle("+id+") >"+value+"</a>";
				}else if(del==2){
					content= "<a style='color: #8D8D8D' onclick=vm.openArticle("+id+")>"+value+"</a>";
				}else{
					content= "<a style='color: #009688' onclick=vm.openArticle("+id+")>" + value + "</a>";
				}
				return content;
				}
			},
			{ label: '创建时间', name: 'createTime',dataType: "date", sortable: true, index: 'create_time',align: "center", width: 140 },
			//{ label: '品牌/分类', name: 'articleTypeName', index: 'articleTypeName',align: "center", width: 80 },
			// { label: '创建者', name: 'userName', index: 'userName',align: "center", width: 50,
			// 	formatter:function(value,options,rowData){
			// 	var source=rowData["articleSource"]
			// 	if(source==1){
			// 		return value;
			// 	}else{
			// 		var userId = rowData["userId"];
			// 		if(value==""){
			// 			return "";
			// 		}else {
			// 			return "<a onclick=vm.openUser("+userId+")>" + value + "</a>";
			// 		}
			// 	}
			// 	}
			// },
			// { label: '分享', name: 'articleShareCount',dataType: "int", sortable: true, index: 'article_share_count',align: "center", width: 40 },
			// { label: '热度', name: 'articleHotScore',dataType: "int", sortable: true, index: 'article_hot_score',align: "center", width: 50
            //     // ,
			// 	// formatter:function(value,options,rowData){
			// 	// 	return value;
			// 	// }
			// },
			// { label: '查看', name: 'articleOutReadCount',dataType: "int", sortable: true, index: 'article_out_read_count',align: "center", width: 40 },
			{ label: '热门', name: 'articleRecommendStatus',sortable: false, index: 'articleRecommendStatus',align: "center", width: 40 ,
				formatter:function(value,options,rowData){
				var content="";
				var id=rowData["id"];
				if( value===0 || value=="" || value==null){
						content="<a style='text-align: center'onclick=vm.updateStatus('"+id+"',3)>"+"否"+"</a>"
					}else if(value==1){
						content="<a style='text-align: center'onclick=vm.updateStatus('"+id+"',4)>"+ "<strong style='color: red'>"+'是'+"</>"+"</a>";
					}
				return content;
				}},
			{ label: '来源', name: 'articleSource', index: 'article_source',align: "center", width: 40 ,
				formatter:function(value,options,rowData){
					var thirdSource=rowData["thirdArticleSource"];
					var source=rowData["articleSource"];
					var content="";
					if(source==1&&thirdSource==1){
						content= "好文";
					}else if(source==1&&thirdSource==2){
						content= "V名片"
					}else if(source==1&&thirdSource!=null&&thirdSource.length>1){
						content= thirdSource;
					}else if( value===1 ){
						content= "平台";
					}else if(value==2){
						content= "用户";
					}else if(value==3){
						content= '用户'
					}else if(value==6){
						content= '入库'
					}
					return content;
				}
			},
			{ label: '状态', name: 'articleStatus', index: 'article_status',align: "center", width: 40 ,
				formatter:function(value,options,rowData){
				var content="";
				if( value===1 ){
					content= '正常';
					}else if(value==0){
					content= "<p style='color: red'>"+'删除'+"</>"
					}else if(value==2){
					content= '隐藏';
					}
				return content;
				}
			},
			{ label: '操作', name: '', index: '',align: "center", width: 130,
				formatter:function(value,options,rowData){
				var status=rowData["articleStatus"];
				var id=rowData["id"];
				var content="";
					if( status===1 ){
						content= "<a style='text-align: center' class='btn btn-primary' onclick=vm.updateStatus('"+id+"',0)>"+"删除"+"</a>";
						// return "<a title='删除'>"+"<i style='font-size: 20px' class='fa fa-trash-o' onclick=vm.updateStatus('"+id+"',0)>"+"</i>"+"</a>"+'&nbsp;&nbsp;'+
                        //     "<a title='热门'>"+"<i style='font-size: 20px' class='fa fa-fire' onclick=vm.updateStatus('"+id+"',3)>"+"</i>"+"</a>";
					}else if(status==0||status==2){
						content= "<a style='text-align: center' class='btn btn-primary' onclick=vm.updateStatus('"+id+"',1)>"+"恢复"+"</a>";
					}
                    content=content+ "<a style='text-align: center' class='btn btn-primary' onclick=vm.editInfo('"+id+"',1)>"+"修改"+"</a>";
					return content;
				}
			}
        ],
		viewrecords: true,
        height: "100%",
        rowNum: 12,
		rowList : [12,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
		postData:{'articleTitle':vm.q.articleTitle,'articleTypeName': vm.q.articleTypeName,"brandId":vm.q.brandId,"source":vm.q.source},
        gridComplete:function(){
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
});
setTimeout(function (){
	$.ajax({
		type: "POST",
		async:false,
		url: baseURL + 'sys/bbrandinfo/queryAll',
		contentType: "application/json",
		success: function(r){
			if(r.code==0){
				//vm.bbrandinfo=r.brandInfo;
				for(var i=0;i<r.brandInfo.length;i++){
					$("#brandName").append(
						"<option value=" + r.brandInfo[i].brandName +">"+"</option>");
				}
			}
		}
	});
}, 2000);
function timesFun (timesData) {
	//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
	var dateBegin = new Date(timesData.replace(/-/g, "/"));//将-转化为/，使用new Date
	var dateEnd = new Date();//获取当前时间
	var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
	var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
	var leave1 = dateDiff % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
	//计算相差分钟数
	var leave2 = leave1 % (3600 * 1000)    //计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000))//计算相差分钟数
	//计算相差秒数
	var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
	var seconds = Math.round(leave3 / 1000);
	var timesString = '';

	if (dayDiff == 0 && hours != 0) {
		timesString = hours;
	}
	return {
		timesString: timesString
	}
}
var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			articleTypeName:"",
			articleTitle:"",
			brandId:"",
			desc:"",
			articleSource:"",
			source:""
		},
		showList: true,
		title: null,
		bArticleInfo: {},
		bbrandinfo:{},
		articleTypeName:null,
		articleTitle:null,
		barticletypeinfo:{},
		pp:'pp',
		lx:'lx',
		page:0
	},
	methods: {
		query: function () {
			vm.q.brandId="";
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.bArticleInfo = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
		},
		status:function(event){
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.bArticleInfo={};
			vm.bArticleInfo.articleStatus=event;
			vm.bArticleInfo.id=id;
			var url = "sys/barticleinfo/update";
			confirm('确定隐藏吗状态？', function() {
				$.ajax({
					type: "POST",
					url: baseURL + url,
					contentType: "application/json",
					data: JSON.stringify(vm.bArticleInfo),
					success: function (r) {
						if (r.code === 0) {
							alert('操作成功', function (index) {
								$("#jqGrid").trigger("reloadGrid");
								//window.location.href="../../../templates/modules/sys/buserinfo.html";
								// window.location.href=baseURL+"sys/permissions/index/"+userId;
							});
						} else {
							alert(r.msg);
						}
					}
				});
			});

		},
		updateStatus: function (ids,event) {
			vm.bArticleInfo={};
			confirm('确定修改状态？', function(){
				if(event==3 || event=="3"){
					vm.bArticleInfo.articleRecommendStatus=1;
				} else if(event==4 || event=="4"){
					vm.bArticleInfo.articleRecommendStatus=0;
				} else{
					vm.bArticleInfo.articleStatus=event;
				}
				vm.bArticleInfo.id=ids;
				console.log(vm.bArticleInfo)
				var url = "sys/barticleinfo/update";
				$.ajax({
					type: "POST",
					url: baseURL + url,
					contentType: "application/json",
					data: JSON.stringify(vm.bArticleInfo),
					success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
								//window.location.href="../../../templates/modules/sys/buserinfo.html";
								// window.location.href=baseURL+"sys/permissions/index/"+userId;
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
        editInfo: function (ids,event) {
            //window.location.href="../sys/barticle_edit.html?id="+ids;
			window.open("../sys/barticle_edit.html?id="+ids);
        },
		addInfo: function (ids,event) {
			//window.location.href="../sys/barticle_edit.html?id="+ids;
			window.open("../sys/barticle_add.html?id="+ids);
		},
		saveOrUpdate: function (event) {
			var url = vm.bArticleInfo.id == null ? "sys/barticleinfo/save" : "sys/barticleinfo/update";
			var selectValue = $(".type option:first").val();
			if(selectValue=='pp'){
				vm.bArticleInfo.articleBrandId=$('.type option:selected').val();
			}else if(selectValue=='lx') {
				vm.bArticleInfo.articleTypeId = $('.type option:selected').val();
			}
			if(vm.bArticleInfo.articleBrandId==""||vm.bArticleInfo.articleBrandId==null||bArticleInfo.articleTitle==""||bArticleInfo.articleTitle==null){
				alert("请输入完整信息");
				return;
			}
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.bArticleInfo),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
        updateInfo: function (event) {
            var url = vm.bArticleInfo.id == null ? "sys/barticleinfo/save" : "sys/barticleinfo/updateInfo";
            //var url =  "sys/barticleinfo/updateInfo";

            //vm.bArticleInfo.articleBrandId=$('#articleBrandId option:selected').val();
            vm.bArticleInfo.brandName=$('#brandName').val();
            vm.bArticleInfo.articleTypeName=$('#articleTypeName').val();

           // console.log( "vm.bArticleInfo.brandName:"+vm.bArticleInfo.brandName);
			//console.log(vm);
            vm.bArticleInfo.articleContent =window.current_editor.getContent();
            //console.log("bArticleInfo Save:"+vm.bArticleInfo);
            if(vm.bArticleInfo.brandName=="" && vm.bArticleInfo.articleTypeName==""){
                alert("请选择品牌或者分类,注意只能选择其中一项");
                return;
            }

            if(vm.bArticleInfo.brandName!="" && vm.bArticleInfo.articleTypeName!=""){
                alert("品牌或者分类,只能选择其中一项");
                return;
            }
			if(vm.bArticleInfo.articleTitle =="" || vm.bArticleInfo.articleDesc =="" || vm.bArticleInfo.articleContent ==""){
				alert("文章标题、概述、内容不能为空！");
				return;
			}

            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json;charset=UTF-8",
                data:JSON.stringify(vm.bArticleInfo),
                dataType: "JSON",
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
							window.close();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		saveInfo: function (event) {
			var url = vm.bArticleInfo.id == null ? "sys/barticleinfo/save" : "sys/barticleinfo/save";

			var strArticleTypeNames="";
			if($(".pArticleTypeName").length>0){
				$(".pArticleTypeName").each(function(){

					strArticleTypeNames=strArticleTypeNames+","+$(this).attr("value");
				});
				strArticleTypeNames=strArticleTypeNames.substring(1);
			}
			vm.bArticleInfo.brandName=strArticleTypeNames;

			// vm.bVideoInfo.brandName=$('#brandName').val();

			vm.bArticleInfo.articleTypeName=$('#articleTypeName').val();

			vm.bArticleInfo.articleContent =window.current_editor.getContent();
			//console.log("bArticleInfo Save:"+vm.bArticleInfo);
			if(vm.bArticleInfo.brandName=="" && vm.bArticleInfo.articleTypeName==""){
				alert("请选择品牌或者分类,注意只能选择其中一项");
				return;
			}

			if(vm.bArticleInfo.brandName!="" && vm.bArticleInfo.articleTypeName!=""){
				alert("品牌或者分类,只能选择其中一项");
				return;
			}
			if(vm.bArticleInfo.articleTitle =="" || vm.bArticleInfo.articleDesc =="" || vm.bArticleInfo.articleContent ==""){
				alert("文章标题、概述、内容不能为空！");
				return;
			}

			$.ajax({
				type: "POST",
				url: baseURL + url,
				contentType: "application/json;charset=UTF-8",
				data:JSON.stringify(vm.bArticleInfo),
				dataType: "JSON",
				success: function(r){
					if(r.code === 0){
						alert('操作成功', function(index){
							window.close();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
        importArticle1: function (event) {
            var url = "sys/barticleinfo/importArticle1";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.bArticleInfo),
                success: function(r){
                    if(r.code === 0){
                        alert('本次待入库文章 '+r.total+' 篇,请稍后刷新文章库.', function(index){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}

			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/barticleinfo/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$("#type").empty();
			$.get(baseURL + "sys/barticleinfo/info/"+id, function(r){
                vm.bArticleInfo = r.bArticleInfo;
                if(r.type==1) {
					$.get(baseURL + "sys/barticletypeinfo/list/", function (r) {
						vm.barticletypeinfo = r.page.list;
						$("#type").append(
							"<option value=" + vm.lx + ">" + '请选择分类' + "</option>");
						for (i = 0; i < vm.barticletypeinfo.length; i++) {
							$("#type").append(
								"<option value=" + vm.barticletypeinfo[i].id + ">" + vm.barticletypeinfo[i].articleTypeName + "</option>");
							$("#type").find("option[value='" + vm.bArticleInfo.articleTypeId + "']").attr("selected", true);
						}
					});
				}else{
					$.get(baseURL + "sys/bbrandinfo/list/", function (r) {
						vm.barticletypeinfo = r.page.list;
						$("#type").append(
							"<option value=" + vm.pp + ">" + '请选择品牌' + "</option>");
						for (i = 0; i < vm.barticletypeinfo.length; i++) {
							$("#type").append(
								"<option value=" + vm.barticletypeinfo[i].id + ">" + vm.barticletypeinfo[i].brandName + "</option>");
							$("#type").find("option[value='" + vm.bArticleInfo.articleBrandId + "']").attr("selected", true);
						}
					});
				}
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = 1;
			console.log(page)
			vm.q.articleTypeName=$("#brandNames").val();
			vm.q.desc=$('#desc option:selected').val();
			vm.q.articleRecommendStatus="";
			var articleSource=$("#articleSource").val();
			var source="";
			if(articleSource=="管理员"){
				source=1;
			}else if(articleSource=="用户"){
				source=2;
			}else if(articleSource=="V名片"){
				source=4;
			}else if(articleSource=="公众号"){
				source=5;
			}else if(articleSource=="入库"){
				source=6;
			}
			$("#jqGrid").jqGrid('setGridParam',{
				url: baseURL + 'sys/barticleinfo/queryList',
				postData:{'desc':vm.q.desc,'articleTitle':vm.q.articleTitle,'articleTypeName': vm.q.articleTypeName,"brandId":vm.q.brandId,"articleRecommendStatus":vm.q.articleRecommendStatus,"source":source},
                page:page
            }).trigger("reloadGrid");
		},
		hot:function () {
			vm.showList = true;
			var page = 1;
			vm.q.articleTypeName=$("#brandNames").val();
			vm.q.articleRecommendStatus=1;
			console.log(vm.q.articleTypeName)
			$("#jqGrid").jqGrid('setGridParam',{
				url: baseURL + 'sys/barticleinfo/queryList',
				postData:{'articleTitle':vm.q.articleTitle,'articleTypeName': vm.q.articleTypeName,"brandId":vm.q.brandId,"articleRecommendStatus":vm.q.articleRecommendStatus},
				page:page
			}).trigger("reloadGrid");
		},
		openArticle:function (e) {
			layer.open({
				type: 2,
				title: '文章信息',
				maxmin: true,
				shadeClose: true, //点击遮罩关闭层
				area : ['420px' , '650px'],
				content: "test.html?id="+e
			});
		},
		openUser:function (e) {
			layer.open({
				type: 2,
				title: '用户信息',
				maxmin: true,
				shadeClose: true, //点击遮罩关闭层
				area : ['600px' , '650px'],
				content: "buserinfo.html?id="+e
			});
		},
		putArticle:function () {
			$.get(baseURL + "sys/barticleinfo/putArticle", function(r){
				if(r.code==0){
					alert("入库成功");
				}
			});
		}
	},
    created:function () {

    }
});
